<template>
  <div>
    <div class="top">
      <div class="search">
        <el-form :inline="true" :model="formInline">
          <!--          <el-form-item label="用户名:">
                      <el-input
                        v-model="formInline.user"
                        placeholder="请输入"
                        clearable
                      />
                    </el-form-item>
                    <el-form-item label="状态:" class="status">
                      <el-select
                        v-model="formInline.status"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option label="启用" value="1" />
                        <el-option label="禁用" value="0" />
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="handleQuery()">查询</el-button>
                    </el-form-item>-->
          <el-form-item>
            <el-button class="add" type="primary" @click="addUser()"
            >{{ t('addUser') }}
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table class="table_content" v-loading="state.dataLoading" :data="state.userList" :border="true">
      <el-table-column prop="user_name" :label="t('userName')"></el-table-column>
      <el-table-column :label="t('userStatue')" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.user_status === 1" type="success">{{ t('open') }}</el-tag>
          <el-tag v-else type="info">{{ t('close') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="role_name" :label="t('roleName')"></el-table-column>
      <el-table-column
        prop="create_time"
        :label="t('createTime')"
      ></el-table-column>
      <el-table-column
        prop="update_time"
        :label="t('updateTime')"
      ></el-table-column>
      <el-table-column :label="t('op')">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"
          >{{ t('configRole') }}
          </el-button
          >
          <el-button type="danger" size="small" @click="handleEnable(row,0)" v-if="row.user_status === 1">{{ t('close')
            }}
          </el-button>
          <el-button type="warning" size="small" @click="handleEnable(row,1)" v-else>{{ t('open') }}</el-button>
          <el-button type="success" size="small" @click="changePwd(row)"
          >{{ t('modifyPwd') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="state.total"
    >
    </el-pagination>
    <!-- 新增or编辑 -->
    <el-dialog :title="addDialogState.dialogTitle" v-loading="addDialogState.shoLoading"
               v-model="addDialogState.dialogVisible" width="500">
      <el-form :model="formItemData">
        <el-form-item :label="t('userName')">
          <el-input v-model="formItemData.user_name" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item :label="t('password')" v-show="isAdd">
          <el-input v-model="formItemData.password" />
        </el-form-item>
        <el-form-item v-show="!isAdd" :label="t('isOpen')">
          <el-switch
            v-model="formItemData.user_status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item :label="t('role')">
          <el-radio-group v-model="formItemData.role_id">
            <el-radio v-for="role in roleList" :key="role.id" :label="role.id">{{ role.role_name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogState.dialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{ t('submit') }}</el-button>
      </template>
    </el-dialog>
    <!-- 修改密码   -->
    <el-dialog :title="t('modifyPwd')" v-loading="modifyPwdDialogState.shoLoading"
               v-model="modifyPwdDialogState.dialogVisible" width="500">
      <el-form :model="changPwdForm">
        <el-form-item :label="t('password')">
          <el-input v-model="changPwdForm.pwd" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modifyPwdDialogState.dialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="submitNewPwd">{{ t('submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, toRefs, onMounted } from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElButton, ElMessage
} from 'element-plus'
import useRoleStore from '@/stores/roleStore'
import { getUserList, doAddUser, doEditUser, doChangePassword } from '@/api/user'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const roleStore = useRoleStore()

const isAdd = ref(false)

const changPwdForm = reactive({
  pwd: '',
  id: ''
})

// 表单数据
const formItemData = ref({
  backend_user_id: '',
  user_name: '',
  password: '',
  role_id: '',
  user_status: 1
})

const state = reactive({
  userList: [],
  currentPage: 1,
  pageSize: 10,
  total: 0,
  dataLoading: false
})

onMounted(async () => {
  _getUserList()
  await roleStore.getRoleList()
})

const { roleList } = storeToRefs(roleStore)

const addDialogState = reactive({
  shoLoading: false,
  dialogVisible: false,
  dialogTitle: ''
})
const modifyPwdDialogState = reactive({
  shoLoading: false,
  dialogVisible: false
})

const _getUserList = () => {
  state.dataLoading = true
  getUserList(state.currentPage, state.pageSize).then(res => {
    state.userList = res.user_list
    state.total = res.total
  }).catch(err => {
    console.log(err)
  }).finally(() => {
    state.dataLoading = false
  })
}

const formInline = reactive({
  user: '',
  status: ''
})


const handleQuery = () => {
  // 处理查询逻辑
  console.log('Query:', formInline)
  _getUserList()
}

const addUser = () => {
  isAdd.value = true
  addDialogState.dialogTitle = t('add')
  formItemData.value = {
    backend_user_id: '',
    user_name: '',
    password: '',
    user_status: 1,
    role_id: ''
  }
  addDialogState.dialogVisible = true
}

const handleEdit = (row) => {
  isAdd.value = false
  addDialogState.dialogTitle = t('edit')
  formItemData.value = {
    backend_user_id: row.id,
    user_name: row.user_name,
    password: row.password,
    role_id: row.role_id,
    user_status: row.user_status
  }
  addDialogState.dialogVisible = true
}

const handleSubmit = () => {
  // 校验formItemData
  if (!formItemData.value.user_name) {
    ElMessage.error(t('userNameEmpty'))
    return
  }
  if (!formItemData.value.password && isAdd.value) {
    ElMessage.error(t('passwordEmpty'))
    return
  }
  if (!formItemData.value.role_id) {
    ElMessage.error(t('roleEmpty'))
    return
  }
  console.log('Submit:', formItemData)
  addDialogState.shoLoading = true
  if (isAdd.value) {
    _doAddUser()
  } else {
    _doEditUser()
  }

}

const _doEditUser = () => {
  doEditUser(formItemData.value.backend_user_id, formItemData.value.user_name,
    formItemData.value.password,
    formItemData.value.role_id, formItemData.value.user_status)
    .then(res => {
      addDialogState.shoLoading = false
      addDialogState.dialogVisible = false
      _getUserList()
    }).catch(err => {
    addDialogState.shoLoading = false
    console.log(err)
  }).finally(() => {
    addDialogState.shoLoading = false
  })
}

const _doAddUser = () => {
  doAddUser(formItemData.value.user_name, formItemData.value.password, formItemData.value.role_id)
    .then(res => {
      addDialogState.shoLoading = false
      addDialogState.dialogVisible = false
      state.currentPage = 1
      _getUserList()
    }).catch(err => {
    addDialogState.shoLoading = false
    console.log(err)
  }).finally(() => {
    addDialogState.shoLoading = false
  })
}

const handleEnable = (row, status) => {
  formItemData.value = {
    backend_user_id: row.id,
    user_name: row.user_name,
    password: row.password,
    role_id: row.role_id,
    user_status: row.user_status == 1 ? 0 : 1
  }
  state.dataLoading = true
  doEditUser(formItemData.value.backend_user_id, formItemData.value.user_name,
    formItemData.value.password,
    formItemData.value.role_id, formItemData.value.user_status)
    .then(res => {
      _getUserList()
    }).catch(err => {
    console.log(err)
  }).finally(() => {
    state.dataLoading = false
  })
}

const changePwd = (row) => {
  changPwdForm.pwd = ''
  changPwdForm.id = row.id
  modifyPwdDialogState.dialogVisible = true
  formItemData.value = {
    backend_user_id: row.id,
    user_name: row.user_name,
    password: row.password,
    role_id: row.role_id,
    user_status: row.user_status
  }
}

const submitNewPwd = () => {
  if (!changPwdForm.pwd) {
    ElMessage.error(t('passwordEmpty'))
    return
  }
  modifyPwdDialogState.shoLoading = true
  doEditUser(formItemData.value.backend_user_id
    , formItemData.value.user_name
    , changPwdForm.pwd
    , formItemData.value.role_id
    , formItemData.value.user_status)
    .then(res => {
      modifyPwdDialogState.dialogVisible = false
      _getUserList()
    }).catch(err => {
    modifyPwdDialogState.shoLoading = false
    console.log(err)
  }).finally(() => {
    modifyPwdDialogState.shoLoading = false
  })
}

const handleSizeChange = (newSize) => {
  state.pageSize = newSize
  _getUserList()
}

const handleCurrentChange = (newPage) => {
  state.currentPage = newPage
  _getUserList()
}

// 导出响应式状态的引用
const { currentPage, pageSize } = toRefs(state)
</script>

<style scoped lang="scss">
.top {
  width: 98%;
  margin-top: 28px;
  margin-bottom: 10px;

  .status {
    width: 180px;
  }
}

.table_content {
  width: 98%;
  margin-top: 20px;
}
</style>
